package com.wzl.producer.controller.rabbitMqController.basicsProducer;

import com.wzl.common.VkPublicResponse;
import com.wzl.producer.config.rabbitMqConfig.RabbitConfig;
import com.wzl.common.constant.VkPublicConstants;
import com.wzl.common.errcode.VkErrorCodeEnum;
import com.wzl.common.pojo.VkSmbmsUser;
import com.wzl.producer.service.rabbitMqService.basicsProducer.MqBasicsProducerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 基础用法生产者
 *
 * @author weizhongli
 * @since 2022-09-04 17:37
 */
@Slf4j
@Controller
public class MqBasicsProducerController {

    @Autowired
    private MqBasicsProducerService mqBasicsProducerService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 测试发送消息
     * @return
     */
    @GetMapping("testProducer/{id}")
    @ResponseBody
    public VkPublicResponse testProducer(@PathVariable("id") int id){
        VkSmbmsUser user = new VkSmbmsUser();
        try {
            user =  mqBasicsProducerService.queryUserById(id);

            RabbitTemplate.ConfirmCallback confirmCallback = (correlationData, ack, cause) -> {
                String messageId = correlationData.getId();
                //返回成功，表示消息被正常投递
                if (ack) {
                    log.info("信息投递成功，messageId:{}",messageId);
                } else {
                    log.error("消费信息失败，messageId:{} 原因:{}",messageId,cause);
                }
            };

            //设置ReturnCallBank
            rabbitTemplate.setReturnCallback((message, i, s, s1, s2) -> System.out.println("return执行了"));

            //设置交换机处理失败消息的模式
            rabbitTemplate.setMandatory(true);
            rabbitTemplate.setConfirmCallback(confirmCallback);
            CorrelationData correlationData = new CorrelationData();
            correlationData.setId(String.valueOf(user.getId()));
            rabbitTemplate.convertAndSend(RabbitConfig.EXCHANGE,RabbitConfig.ROUTING_KEY,user,correlationData);

        } catch (Exception e) {
            e.printStackTrace();
            return new VkPublicResponse(VkErrorCodeEnum.MESSAGE_SEND_ERROR,"消费信息失败，messageId:"+user.getId()+" 原因:"+e.getMessage());
        }
        return new VkPublicResponse(VkPublicConstants.SUCCESS_CODE, VkPublicConstants.SUCCESS_MESSAGE,"信息投递成功，messageId:"+user.getId());
    }


}